#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Filename: login_information.py
# Author: ChenChangSong
# Date: 2025-08-24

"""
功能描述: 登录-测试登录信息btn功能
"""

import json
import openpyxl
import base64
from openpyxl import load_workbook
from comm.common_code import *
from comm.common_code import logger, comm_log, log_to_ui_info, log_to_ui_error
from ui_code.common_ui import clear_screen_logs, get_project_root
from tapd_open_api.login.get_access_token import get_access_token
from tapd_open_api.other_api.get_workspace_info import get_workspace_info

def get_user_info(cookie):
    username = ""
        
    # 一、通过cookie获取用户信息
    url = "https://www.tapd.cn/api/aggregation/user_and_workspace_aggregation/get_user_and_workspace_basic_info?workspace_id=0&location=/my_dashboard"

    # 准备请求头，包含必要的认证信息
    headers = {
    'accept': 'application/json, text/plain, */*',
    'accept-language': 'zh-CN,zh;q=0.9',
    'priority': 'u=1, i',
    'referer': 'https://www.tapd.cn/my_dashboard',
    'sec-ch-ua': '"Not;A=Brand";v="99", "Google Chrome";v="139", "Chromium";v="139"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"',
    'sec-fetch-dest': 'empty',
    'sec-fetch-mode': 'cors',
    'sec-fetch-site': 'same-origin',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36',
    'Cookie': cookie
        }
    response_code, response = api_request(method='GET', url=url, headers=headers)
    # logger.info(f"通过cookie获取用户信息：{response}")
 
    # 初始化返回值
    company_id = ""
    project_id = ""
    console_information = ""

    # 检查响应是否成功且格式正确
    if response_code == 200 and isinstance(response, dict):
        # 检查是否为未登录错误
        if response.get("data") == '':
            # 记录到文件的错误日志
            logger.error("输入的Cookie无效，请重新输入")
            # 记录到界面的错误日志
            log_to_ui_error("输入的Cookie无效，请重新输入")
            return "", "", "", "输入的Cookie无效，请重新输入"
        elif response.get("data") != '':
            # 提取用户信息
            user_data = response.get("data", {}).get("get_current_user_ret", {}).get("data", {})
            username = user_data.get("user_nick", "")
            # log_to_ui_info(f"输入的Cookie有效:")
            console_information += f"输入的Cookie有效:\n"
            # 记录到文件的日志
            console_information += f"用户名:{username}\n"
            
            # 提取公司ID
            company_id = user_data.get("current_company_id", "")
            
            console_information += f"当前公司ID: {company_id}\n"

            # 提取项目信息
            projects = response.get("data", {}).get("my_projects_ret", {}).get("data", {}).get("my_project", {}).get("recently", [])
            if projects and isinstance(projects, list) and len(projects) > 0:
                console_information += f"找到 {len(projects)} 个项目：\n"
                
                for i, project in enumerate(projects):
                    project_id = project.get("id", "")
                    project_name = project.get("project_name", "")
                    console_information += f"项目 {i+1}: 项目ID={project_id}, 项目名称={project_name}\n"

                # 使用第一个项目
                first_project = projects[0]
                project_id = first_project.get("id", "")
                # 记录到文件的日志
                # logger.info(f"默认使用第一个项目(最近访问过的项目)：{first_project.get('project_name', '')}，项目ID：{project_id}")
                console_information += f"默认使用第一个项目(最近访问过的项目)：{first_project.get('project_name', '')}，项目ID：{project_id}\n"

                logger.info(console_information)
                log_to_ui_info(console_information)
                return company_id, project_id, username, console_information
    else:
        # 请求失败，保持字段为空
        # 记录到文件的错误日志
        logger.error(f"请求失败或响应格式不正确: {response_code}, {response}")
        # 记录到界面的错误日志
        log_to_ui_error(f"请求失败或响应格式不正确: {response_code}, {response}")
        return "", "", "", "请求失败或Cookie无效"

def account_and_key_verification(account, key, cookie):
    """测试登录信息(正确则保存) 按钮功能"""
    console_information = ""
    # 1、获取公司ID和项目ID 验证cookie有效,cookie不正确则终止，正确则继续
    company_id, project_id, username, cokie_console_information = get_user_info(cookie)
    if company_id != "" and project_id != "":
        pass
    else:
        message_err = f"Cookie无效，请重新登录"
        # 记录到文件的错误日志
        logger.error(message_err)
        # 记录到界面的错误日志
        log_to_ui_error(message_err)
        
        return False, message_err, None
    # 2、验证账号密码是否正确
    # 获取配置文件路径
    excel_path = get_project_root() / "files" / "config_file" / "confg.xlsx"
    # 确保目录存在
    os.makedirs(os.path.dirname(excel_path), exist_ok=True)

    response_code1,response1 = get_access_token(account, key)
    response_code2,response2 = get_workspace_info(project_id,response1)

    if response_code1 == 200 and response_code2 == 200:
        access_token = response1
        console_information += f"账号：{account}，密钥：****，验证成功！\n"

        # 3、所有输入的信息或默认加载的信息，写入到Excel文件中的第二行
        # 3.1 读取Excel文件
        wb = load_workbook(str(excel_path))
        ws = wb.active
        # 3.2 写入Excel文件
        ws.cell(row=2, column=1, value=company_id)
        ws.cell(row=2, column=2, value=account)
        ws.cell(row=2, column=3, value=key)
        ws.cell(row=2, column=4, value=project_id)
        ws.cell(row=2, column=5, value=username)
        ws.cell(row=2, column=6, value=cookie)
        ws.cell(row=2, column=7, value=access_token)
        wb.save(excel_path)
        # 3.3 写入日志
        # 记录到界面的日志
        console_information += f"公司ID：{company_id}、账号：{account}、密钥：****、项目ID：{project_id}、用户名：{username}、Cookie、access_token，已保存到配置文件成功！\n"
        log_to_ui_info(console_information)
        log_to_ui_info("↑↑↑=================================================↑↑↑")
        return True, console_information, access_token
    else:
        # 记录到文件的错误日志
        logger.error(f"你输入的账号：{account}，或密钥：{key}错误，请重新输入！")
        logger.error("↑↑↑=================================================↑↑↑")
        # 记录到界面的错误日志
        log_to_ui_error(f"你输入的账号：{account}，或密钥：{key}错误，请重新输入！")
        log_to_ui_error("↑↑↑=================================================↑↑↑")
        return False, f"你输入的账号：{account}，或密钥：{key}错误，请重新输入！", None
    
if __name__ == '__main__':
    pass
